package com.netty.go.config;

import com.netty.go.handle.NettyInitialHandle;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class NettyConfig {

    @Resource
    NettyConfigProperties nettyConfigProperties;

    @Resource
    NettyInitialHandle nettyInitialHandle;

    /**
     * 主线程Bean boss线程池-进行客户端连接
     * @return
     */
    @Bean
    public NioEventLoopGroup mainGroup(){
        return new NioEventLoopGroup(nettyConfigProperties.getMain());
    }

    /**
     * 从线程bean  worker线程池-进行业务处理
     * @return
     */
    @Bean
    public NioEventLoopGroup subGroup(){
        return new NioEventLoopGroup(nettyConfigProperties.getSub());
    }


    /**
     * 服务端启动器，监听客户端连接
     * @return
     */
    @Bean
    public ServerBootstrap serverBootstrap(){
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                // 指定使用的线程组
                .group(mainGroup(),subGroup())
                //  指定使用的通道
                .channel(NioServerSocketChannel.class)
                // 指定连接超时时间
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfigProperties.getTimeout())
                // 指定worker处理器
                .childHandler(nettyInitialHandle);
       return serverBootstrap;
    }
}
